package com.example.cmpe277stockdata;

import java.util.ArrayList;

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;

import com.example.cmpe277stockdata.RSSFeeds.HistoricalReader;
import com.example.cmpe277stockdata.beans.HistoricalBean;
import com.example.cmpe277stockdata.beans.NewsBean;
import com.example.cmpe277stockdata.beans.UserBean;
import com.example.cmpe277stockdata.constants.DataConstants;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Spinner;

public class HistoricalActivity extends Activity {
	private String companySymbol,dataSpinnerValue,companyName;
	private HistoricalActivity local;
	private ArrayList<NewsBean> newsList = null; 
	private XYMultipleSeriesDataset mDataset = new XYMultipleSeriesDataset();
	private XYMultipleSeriesRenderer mRenderer = new XYMultipleSeriesRenderer();
	private XYSeries mCurrentSeries;
	private XYSeriesRenderer mCurrentRenderer;
	private Spinner dateSpinner;
	private UserBean user;
	private Button refreshButton;//,companyInfoButton
	
	HistoricalReader reader = new HistoricalReader();
	ArrayList<HistoricalBean> historicalDataList = new ArrayList<HistoricalBean>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_historical);
		
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
		    getActionBar().setDisplayHomeAsUpEnabled(true);
		}
		dateSpinner = (Spinner) findViewById(R.id.period);
		dateSpinner.setBackgroundColor(Color.WHITE);
		clickListnerForSpinneronButtonClick();
		// Set reference to this activity
		local = this;
		newsList = (ArrayList<NewsBean>) getIntent().getSerializableExtra(DataConstants.NEWS_RESULT);
		companyName = getIntent().getStringExtra(DataConstants.COMPANY_NAME);
		companySymbol = getIntent().getStringExtra(DataConstants.TICKER_SYMBOL);
		user = (UserBean) getIntent().getSerializableExtra(DataConstants.USER_DATA);
		HistoricalData histData = new HistoricalData();
		histData.execute();
	}

	public void clickListnerForSpinneronButtonClick() {
		
		refreshButton = (Button) findViewById(R.id.refreshButton);
		//companyInfoButton = (Button) findViewById(R.id.CompanyInfo);

		refreshButton.setOnClickListener(new OnClickListener() {
			 
			  @Override
			  public void onClick(View v) {
					dataSpinnerValue = String.valueOf(dateSpinner.getSelectedItem());				
					HistoricalData histData = new HistoricalData();
					histData.execute();
			  }
		 
			});
		
//		companyInfoButton.setOnClickListener(new OnClickListener() {
//			 
//			  @Override
//			  public void onClick(View v) {
//					Intent companyInfoIntent=new Intent(getApplicationContext(),CompanyInformationActivity.class);
//					startActivity(companyInfoIntent);
//			  }
//		 
//			});
		
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.historical, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch(item.getItemId()) {
	    case R.id.action_home:
	    	if(user != null)
	    	{
	    		Intent intent = new Intent(this, InitialTabContent.class);
				intent.putExtra(DataConstants.USER_DATA, user);
		        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		        startActivity(intent);
	    	}
	    	else
	    	{
	    		Intent intent = new Intent(this, LandingActivity.class);
				intent.putExtra(DataConstants.USER_DATA, user);
		        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		        startActivity(intent);
	    	}
	        
	        return true;
	    case R.id.action_companyNews:
	        Intent intent1 = new Intent(this, NewsActivity.class);
	        intent1.putExtra(DataConstants.NEWS_RESULT, newsList);
        	intent1.putExtra(DataConstants.COMPANY_NAME, companyName);
			intent1.putExtra(DataConstants.USER_DATA, user);
        	intent1.putExtra(DataConstants.TICKER_SYMBOL,companySymbol);
	        intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	        startActivity(intent1);
	        return true;
	    case R.id.action_companyinfo:
	        Intent intent2 = new Intent(this, CompanyInformationActivity.class);
	        intent2.putExtra(DataConstants.NEWS_RESULT, newsList);
        	intent2.putExtra(DataConstants.COMPANY_NAME, companyName);
			intent2.putExtra(DataConstants.USER_DATA, user);
        	intent2.putExtra(DataConstants.TICKER_SYMBOL,companySymbol);
	        intent2.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	        startActivity(intent2);
	        return true;
	    default:
	        return super.onOptionsItemSelected(item);
	    }
	}
	
	public class HistoricalData extends
			AsyncTask<String, Void, ArrayList<HistoricalBean>> {
		private GraphicalView mChart;

		@Override
		protected void onPostExecute(ArrayList<HistoricalBean> result) {
			try {
				if (result != null) {
					historicalDataList = result;
					LinearLayout layout = (LinearLayout) findViewById(R.id.chart);
					if (mChart == null) {
						initChart();
						addSampleData(historicalDataList);
						mChart = ChartFactory.getLineChartView(local, mDataset, mRenderer);
						layout.removeAllViews();
						layout.addView(mChart);
					} else {
						layout.removeAllViews();
						initChart();
						addSampleData(historicalDataList);
						mChart = ChartFactory.getLineChartView(local, mDataset, mRenderer);
						mChart.repaint();
						layout.addView(mChart);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		private void initChart() {
			mCurrentSeries = new XYSeries("Historical Data");
			if(mDataset.getSeries().length > 0)
			mDataset.removeSeries(0);
			mDataset.addSeries(mCurrentSeries);
			if(mRenderer != null && mRenderer.getSeriesRendererCount() > 0 && mCurrentRenderer != null)
			{
				mRenderer.removeSeriesRenderer(mCurrentRenderer);
			}
			mCurrentRenderer = new XYSeriesRenderer();
			mRenderer.addSeriesRenderer(mCurrentRenderer);
			mRenderer.setApplyBackgroundColor(true);
			mRenderer.setBackgroundColor(Color.BLACK);
			mRenderer.setAxesColor(Color.YELLOW);
			mRenderer.setLabelsColor(Color.CYAN);
			mRenderer.setChartTitle("Historical Data for "+ companySymbol);
			mRenderer.setAxisTitleTextSize(16);
			mRenderer.setChartTitleTextSize(20);
			mRenderer.setLabelsTextSize(15);
			mRenderer.setLegendTextSize(15);
			mRenderer.setMargins(new int[] { 20, 30, 15, 0 });
			mRenderer.setPointSize(10);
			mRenderer.setFitLegend(true);
			mRenderer.setInScroll(true);
			mRenderer.setXTitle("Close");
			mRenderer.setYTitle("Open");
		}

		private void addSampleData(ArrayList<HistoricalBean> histData) {
			for (int i = 0; i < histData.size(); i++) {
				if(histData != null)
				mCurrentSeries.add(histData.get(i).getCloseValue(),
						histData.get(i).getOpenValue());
			}
		}

		@Override
		protected ArrayList<HistoricalBean> doInBackground(String... params) {
			ArrayList<HistoricalBean> result = null;
			if (companySymbol != null || !companySymbol.equalsIgnoreCase(""))
				if(dataSpinnerValue == null || dataSpinnerValue.equals(""))
				{
					dataSpinnerValue = "Default";
				}
				result = reader.getHistoricalFields(companySymbol,dataSpinnerValue);// companySymbol
			return result;
		}

	}
}
